package com.clp.protocol.iec104.apdu.asdu.info_obj.info_elem;

import com.clp.protocol.iec104.definition.Ts;
import io.netty.buffer.ByteBuf;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.util.Objects;

/**
 * 双点遥信 信息元素内容
 */
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class M_DP_NA_1_InfoElem extends TsInfoElem {

    /**
     * 有效状态
     */
    private Ts.Valid valid;
    /**
     * 当前值状态
     */
    private Ts.CurrVal currVal;
    /**
     * 被取代状态
     */
    private Ts.Replace replace;
    /**
     * 被闭锁状态
     */
    private Ts.Lock lock;
    /**
     * 开关状态
     */
    private Ts.TwoPointSwitch twoPointSwitch;

    @Override
    public M_DP_NA_1_InfoElem initBy(ByteBuf buf) {
        byte[] bytes = new byte[typeTag().getInfoElemBytesLen()];
        buf.readBytes(bytes);
        byte by = bytes[0];
        this.valid = Ts.Valid.gain((by & 0x80) == 0x80 ? 1 : 0);
        this.currVal = Ts.CurrVal.gain((by & 0x40) == 0x40 ? 1 : 0);
        this.replace = Ts.Replace.gain((by & 0x20) == 0x20 ? 1 : 0);
        this.lock = Ts.Lock.gain((by & 0x10) == 0x10 ? 1 : 0);
        this.twoPointSwitch = Ts.TwoPointSwitch.gain(by & 0x03);
        return this;
    }

    @Override
    public boolean isValid() {
        if (valid == null) return false;
        if (currVal == null) return false;
        if (replace == null) return false;
        if (lock == null) return false;
        return twoPointSwitch == null;
    }

    @Override
    public void writeTo(ByteBuf buf) {
        // TODO 暂时这样
        buf.writeByte(0);
    }

    @Override
    public boolean isTsValid() {
        return valid == Ts.Valid.VALID;
    }

    @Override
    public boolean isTsCurrVal() {
        return currVal == Ts.CurrVal.CURR_VAL;
    }

    @Override
    public boolean isTsReplaced() {
        return replace == Ts.Replace.REPLACE;
    }

    @Override
    public boolean isTsLocked() {
        return lock == Ts.Lock.LOCK;
    }

    @Override
    public boolean isTsSwitchOn() {
        return twoPointSwitch == Ts.TwoPointSwitch.SWITCH_ON;
    }

    @Override
    public String toString() {
        return "有效状态：" + valid + ", 当前值状态：" + currVal + ", 被取代状态：" + replace + ", 被闭锁状态：" + lock + ", 开关状态：" + twoPointSwitch;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        M_DP_NA_1_InfoElem that = (M_DP_NA_1_InfoElem) o;
        return valid == that.valid && currVal == that.currVal && replace == that.replace && lock == that.lock && twoPointSwitch == that.twoPointSwitch;
    }

    @Override
    public int hashCode() {
        return Objects.hash(valid, currVal, replace, lock, twoPointSwitch);
    }
}
